package com.wcfsy.wechat.wx.service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wcfsy.wechat.wx.entity.ClickNumber;
import com.wcfsy.wechat.wx.entity.WechatConfig;
import com.wcfsy.wechat.wx.sys.dao.ActivityMapper;
import com.wcfsy.wechat.wx.util.Constant;
import com.wcfsy.wechat.wx.util.DateStyle;
import com.wcfsy.wechat.wx.util.DateUtil;
import com.wcfsy.wechat.wx.util.HttpClientUtil;
import com.wcfsy.wechat.wx.util.HttpUtil;
import com.wcfsy.wechat.wx.util.WechatUtil;

/**
 *
 * 项目名称：xn-wechat-activity
 * 
 * 类名称：ActivityService.java
 * 
 * 类描述：活动业务层
 * 
 * 创建人： Rod Zhong
 * 
 * 创建时间：2015年7月30日 上午10:53:22
 * 
 * Copyright (c) 深圳市小牛科技有限公司-版权所有
 */
@Service("activityService")
public class ActivityService {

	Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private ActivityMapper activityMapper;
	
	@Resource
	private WechatUtil wechatUtil;
	
	/** 
	* @Title: updateClikckNumber 
	* @Description: 记录点击次数
	* @param @return   
	* @return int   
	* @throws 
	*/
	public ClickNumber updateClickNumber(ClickNumber clickNumber){
		 activityMapper.updateClickNumber(clickNumber);
		 return activityMapper.getClickNumber(clickNumber);
	}
	
	/** 
	* @Title: saveQrCodeEvent 
	* @Description: 保存回调信息
	* @param @param map
	* @param @return   
	* @return int   
	* @throws 
	*/
	public int saveQrCodeEvent(Map<String,Object> map){
		return activityMapper.saveQrCodeEvent(map);
	}
	
	
	/** 
	* @Title: getToken 
	* @Description: 获取到token
	* @param @return
	* @param @throws Exception   
	* @return JSONObject   
	* @throws 
	*/
	public JSONObject getToken() throws Exception{
		//调用SDK 的本地连接
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("appId", wechatUtil.appId);
		map.put("secret", wechatUtil.appSecret);
		map.put("grant_type", Constant.CLIENT_CREDENTIAL);
		logger.info("token = " + map.toString());
		String result = HttpClientUtil.get(Constant.SING_NAME_URL, map);
		if(StringUtils.isEmpty(result)){
			return null;
		}
		JSONObject json = (JSONObject) JSONObject.parse(result);
		WechatConfig wecaht =new WechatConfig();
		wecaht.setToken(json.getString("access_token"));
		wecaht.setType("ticket");
		wecaht.setUpdateTime(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS));
		activityMapper.updateWechatConfig(wecaht);
		return json;
	}
	
	/** 
	* @Title: getWechatTicket 
	* @Description:  获取到的token 入库
	* @param @return   
	* @return WechatConfig   
	* @throws 
	*/
	public WechatConfig getWechatTicket(){
		WechatConfig wechatConfig = new WechatConfig();
		wechatConfig.setType("ticket");
		try {
			JSONObject jsonObject = getToken();
			if(jsonObject != null){
				logger.debug("调用微信获取token接口返回的结果集" + jsonObject.toJSONString());
				String accessToken = jsonObject.getString("access_token");
				if(StringUtils.isNotEmpty(accessToken)){
					// 获取ticket js 签名
					getTicket(wechatConfig,accessToken);
				}else{
					logger.warn("获取accessToken失败！ 返回结果accessToken is null ");
				}
			}else{
				logger.warn("获取token失败！ 返回结果集 is null ");
			}
		} catch (Exception e) {
			logger.warn("获取token失败！" , e );
		}
		return wechatConfig;
	}
	
	/** 
	* @Title: getTicket 
	* @Description: 获取Ticket
	* @param @param wechatConfig
	* @param @param accessToken   
	* @return void   
	* @throws 
	*/
	private void getTicket(WechatConfig wechatConfig,String accessToken){
		wechatConfig.setToken(accessToken);
		//设置token 的值
		Map<String,Object> jsapMap = new HashMap<String,Object>();
		jsapMap.put("access_token", accessToken);
		jsapMap.put("type", Constant.WECHAT_TYPE);
		String jsapiResult = null ;
		try {
			jsapiResult = HttpClientUtil.get(Constant.JSAPI_URL, jsapMap);
			if(jsapiResult != null){
				JSONObject jsapiResultObject = (JSONObject)JSONObject.parse(jsapiResult);
				logger.info("微信token jsapiResultObject: " + jsapiResultObject.toJSONString());
				String ticket = jsapiResultObject.getString("ticket");
				if(StringUtils.isNotEmpty(ticket)){
					// 设置签名的值
					wechatConfig.setTicket(ticket);
					wechatConfig.setUpdateTime(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS));
					activityMapper.updateWechatConfig(wechatConfig);
				}else{
					logger.warn("微信签名失败 ,获取的ticket is null ");
				}
			}else{
				logger.warn("微信签名失败 ,接口返回jsapiResult is null");
			}
		} catch (Exception e) {
			logger.warn("微信签名失败 " , e);
		}
		
	}
	
	public WechatConfig getWechatConfig(){
		WechatConfig wechatConfig = new WechatConfig();
		wechatConfig.setType("ticket");
		WechatConfig wc =  activityMapper.getWechatConfig(wechatConfig);
		if(wc == null){ //如果数据库没有就重新调接口取回token
			wc = getWechatTicket();
		}
		return wc;
	}
	
	/** 
	* @Title: createQrCode 
	* @Description: 调用微信二维码接口
	* @param @param channel
	* @param @return   
	* @return String   
	* @throws 
	*/
	public String createQrCode(String channel){
		if(StringUtils.isNotEmpty(channel)){
			JSONObject token = null;
			try {
				token = JSONObject.parseObject(JSON.toJSONString(getWechatConfig()));
				logger.info("token = " + token);
			} catch (Exception e) {
				logger.error("get token error ！" , e);
				return WechatUtil.resultMessage(-1,"token is null");
			}
			if(token != null && StringUtils.isNotEmpty(token.getString("access_token"))){
				JSONObject postRequest = new JSONObject();
				JSONObject scene = new JSONObject();
				JSONObject scene_str = new JSONObject();
				scene_str.put("scene_str", channel);
				scene.put("scene", scene_str);
				postRequest.put("action_name", Constant.ACTION_NAME);
				postRequest.put("action_info", scene);
				try {
					logger.info("request param : " + postRequest.toJSONString()+"\n");
					String result = HttpUtil.getInstance().phpPost(Constant.QR_CODE + token.getString("access_token"), postRequest);
					logger.info(" result : " + result);
					JSONObject resultObject = (JSONObject)JSONObject.parse(result);
					String ticket = resultObject.getString("ticket");
					if(StringUtils.isNotEmpty(ticket)){
						String getQrticketUrl = Constant.GET_TICKET_URL + ticket;
						JSONObject qrImage = new JSONObject();
						String resultJson = WechatUtil.resultMessage(0,"success",qrImage);
						qrImage.put("qrImage", getQrticketUrl);
						Map<String ,Object> map = new HashMap<String ,Object>();
						map.put("qrImage", getQrticketUrl);
						map.put("ticket", ticket);
						map.put("channel", channel);
						map.put("createDate", DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS));
						activityMapper.saveQRImageAndTicket(map);
						return resultJson;
					}else{
						logger.info("ticket error");
						return WechatUtil.resultMessage(-1,"ticket error");
					}
				} catch (Exception e) {
					logger.error("qr error" , e);
					return WechatUtil.resultMessage(-1,"qr error");
				}
			}else{
				logger.error("token is null ");
				return WechatUtil.resultMessage(-1,"token is null");
			}
		}else{
			logger.error("channel is null");
			return WechatUtil.resultMessage(-1,"channel is null");
		}
	}
	
	/**
	 *  定时器获取环信的token
	 * @param map
	 */
	public void saveIMToken(Map<String,String> map){
		activityMapper.saveIMToken(map);
	}
	
	/**
	 * 获取token
	 * @return
	 */
	public String getIMToken(){
		return activityMapper.getIMToken();
	}
}
